package net.oschina.app.base;

import android.graphics.Color;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import net.oschina.app.R;
import net.oschina.app.protocol.AccessProtocol;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Shinelon on 2017/1/15.
 */

public abstract class BaseListFragment extends BaseFragment {
    @BindView(R.id.rv)
    RecyclerView mRv;
    @BindView(R.id.srl)
    SwipeRefreshLayout mSrl;
    private AccessProtocol mProtocol;
    private BaseListAdapter mAdapter;
    private Handler mHandler = new Handler();

    @Override
    public int getLayoutRes() {
        return R.layout.fragment_list;
    }

    @Override
    public void initView() {
        ButterKnife.bind(this, mRoot);
        mSrl.setColorSchemeColors(Color.parseColor("#ff0000"),
                Color.parseColor("#00ff00"), Color.parseColor("#0000ff"),
                Color.parseColor("#ffff00"));

    }

    @Override
    public void initListener() {
        mSrl.setOnRefreshListener(listener);
    }

    @Override
    public void initData() {
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        mRv.setLayoutManager(manager);
        mAdapter = getAdapter();
        /*mRv.addItemDecoration(new DividerItemDecoration(getContext(),
                DividerItemDecoration.VERTICAL));*/

        mRv.setAdapter(mAdapter);
        if (mAdapter!=null){
            mRv.setAdapter(mAdapter);
        }


        mProtocol = getProtocol();
        accessNetGetData();
    }

    private void accessNetGetData() {
        if (mProtocol!=null){
            mProtocol.setOnAccessNetListener(onAccessNetListener);
            mProtocol.getData();
        }
    }

    SwipeRefreshLayout.OnRefreshListener listener = new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    accessNetGetData();
                    mSrl.setRefreshing(false);
                }
            }, 3000);
        }
    };

    AccessProtocol.onAccessNetListener onAccessNetListener = new AccessProtocol.onAccessNetListener() {
        @Override
        public void onSuccess() {
            Object body = mProtocol.getBody();
            if (body!=null){
                mAdapter.setData(parseData(body));
            }
            mSrl.setRefreshing(false);
        }

        @Override
        public void onFail() {
            mSrl.setRefreshing(false);
        }
    };

    protected abstract List parseData(Object body);

    protected abstract AccessProtocol getProtocol();

    protected abstract BaseListAdapter getAdapter();
}
